<template>
  <div>
    <el-from>
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="食宿费用" name="first">
          <el-button type="primary" @click="addFN">新建酒店</el-button>
          <el-button type="success" @click="importHotel">导入酒店</el-button>
          <br />
          <br />

          <el-table :data="hotelList">
            <el-table-column
              label="序号"
              width="50px"
              type="index"
              align="center"
            ></el-table-column>
            <el-table-column
              label="酒店名称"
              min-width="100"
              prop="name"
              align="center"
            ></el-table-column>
            <el-table-column
              label="酒店地址"
              min-width="200"
              prop="address"
              align="center"
            ></el-table-column>
            <el-table-column
              label="房型"
              min-width="120"
              prop="houseType"
              align="center"
            ></el-table-column>
            <el-table-column
              label="价格"
              min-width="120"
              prop="spend"
              align="center"
            ></el-table-column>
            <el-table-column
              label="入住时间"
              min-width="140"
              prop="moveIntoTime"
              align="center"
            ></el-table-column>
            <el-table-column
              label="离店时间"
              min-width="140"
              prop="leaveTime"
              align="center"
            ></el-table-column>
            <el-table-column
              label="餐食"
              min-width="120"
              prop="haveDinner"
              align="center"
            >
              <template #default="scope">
                <el-tag
                  v-if="scope.row.haveDinner == 1"
                  type="success"
                  class="mx-1"
                  effect="dark"
                  round
                  >是
                </el-tag>
                <el-tag v-else type="success" class="mx-1" effect="plain" round
                  >否
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="房间数量"
              min-width="120"
              prop="houseCount"
              align="center"
            >
            </el-table-column>
            <el-table-column
              label="备注"
              min-width="120"
              prop="remarks"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center" width="200">
              <template #default="scope">
                <el-button
                  type="text"
                  @click="hotUpdateFN(scope.row)"
                  icon="Edit"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  @click="hotelDetail(scope.row)"
                  icon="More"
                  >详情</el-button
                >
                <el-button
                  type="text"
                  @click="hotDelFN(scope.row)"
                  icon="Delete"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="其它费用" name="last">
          <el-button
            type="primary"
            :icon="Plus"
            @click="showDialogOther = 'true'"
            >新增费用</el-button
          >
          <br />
          <br />

          <el-table :data="otherList">
            <el-table-column
              label="序号"
              width="80"
              align="center"
              type="index"
            ></el-table-column>
            <el-table-column
              label="费用名称"
              min-width="120"
              prop="name"
              align="center"
            ></el-table-column>
            <el-table-column
              label="价格"
              min-width="120"
              prop="spend"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" min-width="120" align="center">
              <template #default="scope">
                <el-button
                  type="text"
                  @click="otherUpdateFN(scope.row)"
                  icon="Edit"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  @click="otherDelFN(scope.row)"
                  icon="Delete"
                  >删除</el-button
                >
              </template></el-table-column
            >
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-from>
    <br />
    <br />
    <el-row justify="center">
      <el-button type="primary" v-if="route.query.id" @click="goUP"
        >上一步</el-button
      >
      <el-button type="primary" @click="xiaFN(id)">下一步</el-button>
    </el-row>
    <!-- 新建酒店 -->

    <el-dialog
      v-model="showDialog"
      width="70%"
      append-to-body
      center
      draggable
      @close="close"
      v-if="showDialog"
      :title="addForm.id ? '编辑酒店' : '新建酒店'"
    >
      <el-form ref="Dialog" :model="addForm" label-width="145px" :rules="rules">
        <el-row>
          <el-form-item label="酒店名称：" prop="name" style="width: 500px">
            <el-input v-model="addForm.name" placeholder="请输入酒店名称" />
          </el-form-item>
          <el-form-item label="酒店地址：" prop="address" style="width: 500px">
            <el-input placeholder="请输入酒店地址" v-model="addForm.address" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="房型：" prop="houseType" style="width: 500px">
            <el-input
              placeholder="请输入酒店房型"
              v-model="addForm.houseType"
            />
          </el-form-item>
          <el-form-item label="费用：" prop="spend" style="width: 500px">
            <el-input type="number" v-model="addForm.spend" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="入住时间:"
            prop="moveIntoTime"
            style="width: 500px"
          >
            <el-date-picker
              style="width: 500px"
              v-model="addForm.moveIntoTime"
              type="datetime"
              placeholder="入住时间"
              size="large"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item
            label="离店时间："
            prop="leaveTime"
            style="width: 500px"
          >
            <el-date-picker
              style="width: 500px"
              v-model="addForm.leaveTime"
              type="datetime"
              placeholder="离店时间"
              size="large"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="可餐：" prop="haveDinner" style="width: 500px">
            <el-radio-group v-model="addForm.haveDinner">
              <el-radio :label="1" size="large">是</el-radio>
              <el-radio :label="0" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="房间数量："
            prop="houseCount"
            style="width: 500px"
          >
            <el-input type="number" v-model="addForm.houseCount" />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="备注：" prop="remarks" style="width: 500px">
            <el-input
              placeholder="请写备注信息"
              v-model="addForm.remarks"
              :rows="2"
              type="textarea"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="上传图片：" prop="pic">
            <imageUpload2 :limit="1" v-model="addForm.pic" />
          </el-form-item>
        </el-row>
      </el-form>
      <br />
      <br />
      <el-row justify="center">
        <el-button type="primary" @click="submitFN">保 存</el-button>
      </el-row>
      <br />
      <br />
    </el-dialog>

    <!-- 其他费用弹框 -->
    <el-dialog
      v-model="showDialogOther"
      width="30%"
      append-to-body
      center
      draggable
      @close="closeOther"
      v-if="showDialogOther"
      :title="addForm.id ? '编辑费用' : '新增费用'"
    >
      <el-form
        ref="DialogOther"
        :model="addForm"
        label-width="120px"
        :rules="rules1"
      >
        <el-form-item label="费用名称：" prop="name">
          <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="价 格:" prop="spend">
          <el-input type="number" v-model="addForm.spend" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="btnOkFN">确 定</el-button>
          <el-button type="warning" @click="warningFN">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 导入酒店弹框 -->
    <el-dialog
      v-model="showImport"
      width="30%"
      append-to-body
      center
      draggable
      @close="closeFN"
      v-if="showImport"
      title="导入酒店"
    >
      <el-tree
        ref="treeRef"
        :data="importList"
        show-checkbox
        default-expand-all
        node-key="id"
        highlight-current
        :props="defaultProps"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="importFN">导 入</el-button>
          <el-button type="primary" @click="toggleSelection">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--酒店详情弹窗-->
    <dialogAddHotel :props="dialogProps" @submitForm="resetQuery" />
  </div>
</template>
<script setup name="TrainCost">
import {
  trainCostList,
  trainCostAdd,
  trainCostUpdate,
  trainCostDel,
  trainCostImport,
  trainCostImportAdd,
} from "@/api/train/TrainCost.js";
import dialogAddHotel from "../TrainCost/dialog/hotelDetail";
import { getCurrentInstance } from "vue";
import { reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();
const dialogPropsBase = {
  open: false,
  isView: false,
  title: "",
  data: null,
};
const dialogProps = reactive({
  ...dialogPropsBase,
});
const props = defineProps({
  id: {},
  projectId: {},
});

const id = ref(props.id);
const { proxy } = getCurrentInstance();
const showDialog = ref(false);
const showDialogOther = ref(false);
const hotelList = ref([]);
const otherList = ref([]);
const activeName = ref("first");
const Dialog = ref();
const showImport = ref(false);
const DialogOther = ref();
const importList = ref();
const emit = defineEmits(["xiaFN"]);

const treeRef = ref();
const picLength = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("请上传图片"));
  }
  callback();
};
const data = reactive({
  addForm: {},
  rules: {
    pic: [
      { required: true, trigger: "blur", message: "请上传图片" },
      { validator: picLength, trigger: "blur" },
    ],
    name: [{ required: true, message: "酒店名称不能为空", trigger: "blur" }],

    address: [{ required: true, message: "酒店地址不能为空", trigger: "blur" }],
    houseType: [
      { required: true, message: "酒店房型不能为空", trigger: "blur" },
    ],

    haveDinner: [
      {
        required: true,
        message: "请选择",
        trigger: "change",
      },
    ],
    moveIntoTime: [
      {
        required: true,
        message: "请选择一个日期",
        trigger: "change",
      },
    ],
    leaveTime: [
      {
        required: true,
        message: "请选择一个日期",
        trigger: "change",
      },
    ],
    houseCount: [
      { required: true, message: "房间数量不能为空", trigger: "blur" },
    ],

    remarks: [{ required: true, message: "备注不能为空", trigger: "blur" }],
    nameOther: [
      { required: true, message: "费用名称不能为空", trigger: "blur" },
    ],
    spend: [{ required: true, message: "费用价格不能为空", trigger: "blur" }],
  },
  rules1: {
    name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
    spend: [{ required: true, message: "费用不能为空", trigger: "blur" }],
  },
  train: {
    id: props.id,
  },
});
const { addForm, rules, train, rules1 } = toRefs(data);

initData();
// 获取酒店信息
async function initData() {
  let res = await trainCostList(train.value);
  hotelList.value = res.data.hotelList;
  otherList.value = res.data.otherList;
}

// 新增按钮
function addFN() {
  showDialog.value = true;
}

// 对话框关闭
function close() {
  showDialog.value = false;
  initData();
  addForm.value = {};
}

// 保存按钮
async function submitFN() {
  proxy.$refs["Dialog"].validate(async (valid) => {
    if (valid) {
      addForm.value.hotelOrOther = 0;
      if (addForm.value.id) {
        // 编辑
        addForm.value.pic = addForm.value.pic.split(",");
        await trainCostUpdate(addForm.value);
      } else {
        // 新增
        addForm.value.trainId = train.value.id;
        addForm.value.pic = addForm.value.pic.split(",");
        await trainCostAdd(addForm.value);
      }
      //   关闭弹框
      close();
    } else {
      proxy.$modal.msgError("请完善信息");
    }
  });
  // 表单验证
  // debugger;
  // await Dialog.value.validate((valid) => {
  //   console.log(valid);
  //   if (!valid) {
  //     return false;
  //   }
  // });

  // addForm.value.hotelOrOther = 0;
  // if (addForm.value.id) {
  //   // 编辑
  //   addForm.value.pic = addForm.value.pic.split(",");
  //   await trainCostUpdate(addForm.value);
  // } else {
  //   // 新增
  //   addForm.value.trainId = train.value.id;
  //   addForm.value.pic = addForm.value.pic.split(",");
  //   await trainCostAdd(addForm.value);
  // }
  // //   关闭弹框
  // close();
}
// 编辑按钮
function hotUpdateFN(row) {
  showDialog.value = true;
  addForm.value = row;
  addForm.value.haveDinner = parseInt(addForm.value.haveDinner);
  addForm.value.pic = JSON.parse(row.pic).join();
}

//食宿 删除按钮
function hotDelFN(row) {
  // clearTimeout(timer);
  let timer = "";
  proxy.$modal
    .confirm('是否确认删除酒店名称为"' + row.name + '"的数据项？')
    .then(function () {
      addForm.value.ids = row.id;
      trainCostDel(addForm.value);
      timer = setTimeout(() => {
        initData();
      }, 500);
    })
    .then(() => {
      addForm.value = {};
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

//其他 确定
async function btnOkFN() {
  // 表单验证
  try {
    await DialogOther.value.validate();
  } catch (error) {
    console.log(error);
    return false;
  }
  addForm.value.hotelOrOther = 1;

  if (addForm.value.id) {
    // 编辑
    await trainCostUpdate(addForm.value);
  } else {
    // 新增
    addForm.value.trainId = train.value.id;
    await trainCostAdd(addForm.value);
  }
  showDialogOther.value = false;
  initData();
  addForm.value = {};
}

//其他 编辑
async function otherUpdateFN(row) {
  addForm.value = row;
  showDialogOther.value = true;
}

//其他 删除
function otherDelFN(row) {
  proxy.$modal
    .confirm('是否确认删除费用名称为"' + row.name + '"的数据项？')
    .then(function () {
      addForm.value.ids = row.id;
      trainCostDel(addForm.value);
    })
    .then(() => {
      initData();
      addForm.value = {};
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

// 取消
function warningFN() {
  showDialogOther.value = false;
}

// 下一步
function xiaFN(id) {
  emit("xiaFN", 3, id, props.projectId);
}

function goUP(id) {
  emit("xiaFN", 1, id, props.projectId);
}

// 获取导入酒店
async function importHotel() {
  showImport.value = true;
  addForm.value.projectId = props.projectId;
  if (route.query.projectId) addForm.value.projectId = route.query.projectId;

  let res = await trainCostImport(addForm.value);
  importList.value = res.data;
}

// 树形控件数据绑定
const defaultProps = {
  children: "hotelList",
  label: "name",
};

// 关闭导入弹框
function closeFN() {
  showImport.value = false;
  initData();
  addForm.value = {};
}

// 导入
async function importFN() {
  addForm.value = {};
  let res = treeRef.value.getCheckedNodes();
  res = JSON.parse(JSON.stringify(res));
  let arr = res.filter((item) => {
    return item.id;
  });
  let arrList = arr.map((item) => {
    return item.id;
  });
  addForm.value.trainId = train.value.id;
  addForm.value.hotelIds = arrList;
  console.log(addForm.value);
  await trainCostImportAdd(addForm.value);
  closeFN();
}

// 导入酒店取消
const toggleSelection = () => {
  treeRef.value.setCheckedKeys([]);
  closeFN();
};

//查看酒店详情
function hotelDetail(row) {
  _.assign(dialogProps, dialogPropsBase, {
    open: true,
    isView: true,
    title: "酒店信息详情",
    // trainId: trainId,
    // userId: route.params.userId
    data: { ...row },
  });
}

function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
</script>

<style scope></style>
